package com.hospital.data.simulation.utils;

import com.hospital.data.simulation.config.properties.PdfContentProperties;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;

@Component
public class PDFGenerator {

    @Autowired
    private PdfContentProperties pdfContentProperties;
    @Value("${pdf.font.path}")
    private String fontPath;

    public ByteArrayOutputStream generateFormattedPdf(String bodyText) throws Exception {
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, outputStream);

        // 设置文档属性
        document.addTitle(pdfContentProperties.getTitle());
        document.addAuthor(pdfContentProperties.getAuthor());

        document.open();

        // 设置字体（支持中文）
        BaseFont baseFont = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        Font titleFont = new Font(baseFont, 16, Font.BOLD);
        Font headerFont = new Font(baseFont, 12, Font.BOLD);
        Font bodyFont = new Font(baseFont, 12, Font.NORMAL);
        Font footerFont = new Font(baseFont, 10, Font.ITALIC);

        // 添加标题
        Paragraph title = new Paragraph(pdfContentProperties.getTitle(), titleFont);
        title.setAlignment(Element.ALIGN_CENTER);
        title.setSpacingAfter(20f);
        document.add(title);

        // 添加页眉
        Paragraph header = new Paragraph(pdfContentProperties.getHeader(), headerFont);
        header.setAlignment(Element.ALIGN_LEFT);
        header.setSpacingAfter(10f);
        document.add(header);

        // 添加正文
        Paragraph body = new Paragraph(bodyText, bodyFont);
        body.setAlignment(Element.ALIGN_JUSTIFIED);
        body.setSpacingAfter(20f);
        document.add(body);

        // 添加页脚
        Paragraph footer = new Paragraph(pdfContentProperties.getFooter(), footerFont);
        footer.setAlignment(Element.ALIGN_RIGHT);
        document.add(footer);

        document.close();
        return outputStream;
    }
}
